module util_STT
    implicit none
contains

function var(buf, st, ed)
    real(8), intent(in), dimension(:) :: buf
    integer, intent(in) :: st, ed
    integer :: i,n
    real(8) :: sqsum, sum, var
    n=ed-st+1
    sqsum=0
    sum=0
    do i=st, ed
        sqsum = sqsum + buf(i)**2
        sum = sum+buf(i)
    end do
    var = (sqsum-sum**2/n)/(n-1)
    
end function

function stdev(buf, st, ed)
    real(8), intent(in), dimension(:) :: buf
    integer, intent(in) :: st, ed
    integer :: i,n
    real(8) :: var, sqsum, sum, stdev
    n=ed-st+1
    sqsum=0
    sum=0
    do i=st, ed
        sqsum = sqsum + buf(i)**2
        sum = sum+buf(i)
    end do
    var = (sqsum-sum**2/n)/(n-1)
    stdev=sqrt(var)
end function

function stdevp(buf, st, ed)
    real(8), intent(in), dimension(:) :: buf
    integer, intent(in) :: st, ed
    integer :: i,n
    real(8) :: var, sqsum, sum, stdevp
    n=ed-st+1
    sqsum=0
    sum=0
    do i=st, ed
        sqsum = sqsum + buf(i)**2
        sum = sum+buf(i)
    end do
    var = (sqsum-sum**2/n)/(n)
    stdevp=sqrt(var)
end function

function covarlag(buf, st, ed, lag)
    real(8), intent(in), dimension(:) :: buf
    integer, intent(in) :: st, ed, lag
    real(8) :: xt, xs, psum, covarlag
    integer :: i, n
    n = ed-st-lag+1
    xt = sum(buf(st : ed-lag))/n
    xs = sum(buf(st+lag : ed))/n
    psum = 0.
    do i=st, ed-lag
        psum = psum+buf(i)*buf(i+lag)
    end do
    psum = psum/n
    covarlag = psum-xt*xs
end function

end module